<?php
namespace api\modules\v1\models\circle;

use api\modules\v1\models\friend\Friend;
use api\modules\v1\models\user\User;
use api\modules\v1\models\userLevel\UserLevel;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\Status;
use common\models\user\UserViewLog;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

class CircleUserRelation extends \common\models\circle\CircleUserRelation
{
    /**
     * 点赞圈子
     * @return array
     */
    public function like() {
        $trans = static::getDb()->beginTransaction();

        try {
            $id = Yii::$app->request->post('id','');
            if (!$id) {
                throw new Exception('参数错误！');
            }

            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $where['status'] = Status::COMMON_CHECKING_SUCCESS;
            $where['id'] = $id;
            $info = Circle::getOneByWhere($where);
            if (!$info) {
                throw new Exception('信息不存在！');
            }

//            if($info['user_id'] != $user['id']) {
//                //是否是好友
//                $isFriendWhere = $isFriendAndWhere = [];
//                $isFriendWhere['user_id'] = $user['id'];
//                $isFriendWhere['friend_id'] = $info['user_id'];
//                $isFriend = Friend::getOneByWhere($isFriendWhere,'id');
//                if (empty($isFriend)) {
//                    throw new Exception('您和他不是好友，不能查看！');
//                }
//            }

            $data['circle_id'] = $id;
            $data['user_id'] = $user['id'];
            $data['type'] = Status::CIRCLE_USER_RELATION_TYPE_LIKE;
            $check = static::getOneByWhere($data);
            if (!$check) {
                $data['create_time'] = date('Y-m-d H:i:s');
                $data['topic_user_id'] = $info['user_id'];
                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                $handleName = '点赞';

                $res = Circle::updateAllCounters(['like_num' => 1], ['id' => $id]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                $likeNum = $info['like_num'] + 1;

                // 未读数量
                (new FriendApply())->notReadApplyNum($info['user_id'],0,'',date('Y-m-d H:i:s'),"{$user['nick_name']}赞了你的动态，和他聊聊");
            } else {
                $res = static::deleteAll(['id' => $check['id']]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }
                $handleName = '取消点赞';

                $res = Circle::updateAllCounters(['like_num' => -1], ['id' => $id]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }
                $likeNum = $info['like_num'] - 1;
            }
            $return['like_num'] = (int) $likeNum;


            $trans->commit();
            return Functions::formatRestAPI(0, $handleName.'成功',$return);
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 收藏
     * @return array
     */
    public function collection() {
        $trans = static::getDb()->beginTransaction();

        try {
            $id = Yii::$app->request->post('id','');
            if (!$id) {
                throw new Exception('参数错误！');
            }

            $user = Yii::$app->getUser()->getIdentity()->toArray();

            $where['is_delete'] = Status::COMMON_IS_NOT_DELETE;
            $where['status'] = Status::COMMON_CHECKING_SUCCESS;
            $where['id'] = $id;
            $info = Circle::getOneByWhere($where);
            if (!$info) {
                throw new Exception('信息不存在！');
            }

//            if($info['user_id'] != $user['id']) {
//                //是否是好友
//                $isFriendWhere = $isFriendAndWhere = [];
//                $isFriendWhere['user_id'] = $user['id'];
//                $isFriendWhere['friend_id'] = $info['user_id'];
//                $isFriend = Friend::getOneByWhere($isFriendWhere,'id');
//                if (empty($isFriend)) {
//                    throw new Exception('您和他不是好友，不能查看！');
//                }
//            }

            $data['circle_id'] = $id;
            $data['user_id'] = $user['id'];
            $data['type'] = Status::CIRCLE_USER_RELATION_TYPE_COLLECT;
            $check = static::getOneByWhere($data);
            if (!$check) {
                $data['topic_user_id'] = $info['user_id'];
                $data['create_time'] = date('Y-m-d H:i:s');
                $res = static::insertData($data);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                $handleName = '收藏';

                $res = Circle::updateAllCounters(['collect_num' => 1], ['id' => $id]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }

                $collectNum = $info['collect_num'] + 1;
            } else {
                $res = static::deleteAll(['id' => $check['id']]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }
                $handleName = '取消收藏';

                $res = Circle::updateAllCounters(['collect_num' => -1], ['id' => $id]);
                if ($res === false) {
                    throw new Exception('操作失败！');
                }
                $collectNum = $info['collect_num'] - 1;
            }
            $return['collect_num'] = (int) $collectNum;

//            // 未读数量 收藏无需发送未读信息
//            (new FriendApply())->notReadApplyNum($info['user_id']);
            $trans->commit();
            return Functions::formatRestAPI(0, $handleName.'成功', $return);
        } catch (Exception $e) {
            $trans->rollBack();
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

    /**
     * 浏览记录
     * @param array $info
     * @param array $user
     * @return bool
     * @throws Exception
     */
    public function view($info = [], $user = []) {

        if (empty($info) || empty($user)) {
            return true;
        }

//        if($info['user_id'] != $user['id']) {
//            //是否是好友
//            $isFriendWhere = $isFriendAndWhere = [];
//            $isFriendWhere['user_id'] = $user['id'];
//            $isFriendWhere['friend_id'] = $info['user_id'];
//            $isFriend = Friend::getOneByWhere($isFriendWhere,'id');
//            if (empty($isFriend)) {
//                return true;
//            }
//        }

        $data['circle_id'] = $info['id'];
        $data['user_id'] = $user['id'];
        $data['type'] = Status::CIRCLE_USER_RELATION_TYPE_VIEW;
        $data['topic_user_id'] = $info['user_id'];
        $check = static::getOneByWhere($data);
        if (!$check) {
            $data['create_time'] = date('Y-m-d H:i:s');
            $res = static::insertData($data);
            if ($res === false) {
                throw new Exception('操作失败！');
            }
        } else {
            //修改时间
            static::updateData(['create_time' => date('Y-m-d H:i:s')],['id' => $check['id']]);
        }
        //添加浏览量
        Circle::updateAllCounters(['view_num' => 1], ['id' => $info['id']]);

        return true;
    }

    /**
     * 收到的 点赞  收藏列表
     * @return array
     */
    public function getRelationList()
    {
        try{
            $page = (int) Yii::$app->request->get('page',1);
            $size = (int) Yii::$app->request->get('size',20);
            $type = (int) Yii::$app->request->get('type','');
            $code = Yii::$app->request->get('code','');

            $user = Yii::$app->getUser()->getIdentity()->toArray();
            $levelInfo = UserLevel::getOneInfoById($user['level_id']);
            $where = $andWhere = [];
            if ($type == Status::CIRCLE_USER_RELATION_TYPE_LIKE) {
                $where['type'] = Status::CIRCLE_USER_RELATION_TYPE_LIKE;
            }else if($type == Status::CIRCLE_USER_RELATION_TYPE_COLLECT){
                $where['type'] = Status::CIRCLE_USER_RELATION_TYPE_COLLECT;
            }else{
                throw new Exception('参数错误！');
            }
            $userId = $user['id'];
            // 查看具体某个用户
            if($code){
                $viewUser = User::getOneByWhere(['tx_code'=>$code]);
                $userId = $viewUser['id'];
                if(empty($viewUser)){
                    throw new Exception('未知用户');
                }
            }

            $where['topic_user_id'] = $userId;
//            $count = static::getCountByAndWhere($where,$andWhere);
//            $data = static::setPageinationAPI($page, $size, $count);


//            $longitude = $this->getLongitude() ? $this->getLongitude() : '116.3424590000';
//            $latitude = $this->getLatitude() ? $this->getLatitude() : '39.91024';
            list($longitude,$latitude) = $this->getPosition($user['phone']);

            $data = static::setPaginationForApi($page);
            $offset = ($page - 1) * $size;
            $list = static::getObjectByAndWhere($where, $andWhere, ['*'], 'is_read DESC, id DESC', $offset, $size)
                ->with([
                    'user' => function ($q) use($longitude,$latitude) {
                    $distanceField = "ROUND(
                6378.138 * 2 * ASIN(
                    SQRT(
                        POW(
                            SIN(
                                (
                                    {$latitude} * PI() / 180 - latitude * PI() / 180
                                ) / 2
                            ),
                            2
                        ) + COS({$latitude} * PI() / 180) * COS(latitude * PI() / 180) * POW(
                            SIN(
                                (
                                    {$longitude} * PI() / 180 - longitude * PI() / 180
                                ) / 2
                            ),
                            2
                        )
                    )
                ),5 
            ) AS distance";
                    $q -> select(['id','nick_name','tx_code','user_face','sex','birthday','level_id','is_hiding',$distanceField]);
                },
                    'circle' => function ($q) {
                        $q -> select(['id','title','images']);
                    },
                ])
                ->asArray()->all();

            $result = [];
            foreach ($list as $v) {
                $singleUserInfo = ArrayHelper::getValue($v,'user',[]);
                $singleCircleInfo = ArrayHelper::getValue($v,'circle',[]);

                $imageTmp = [];
                $imageArray = $singleCircleInfo['images'] ? json_decode($singleCircleInfo['images'],true) : [];
                if ($imageArray) {
                    foreach ($imageArray as $vv) {
                        $imageTmp[] = $this->imageHost . $vv;
                    }
                }

                $tmp = [
                    'id' => (int) $v['id'],
                    'user_id' => $singleUserInfo['id'] ?: '',
                    'nick_name' => $singleUserInfo['nick_name'] ?? '',
                    'tx_code' => $singleUserInfo['tx_code'],
                    'face' => static::getAvatar($singleUserInfo['user_face']),
                    'circle_id' => $singleCircleInfo['id'] ?? '',
                    'title' => $singleCircleInfo['title'] ?? '',
                    'images' => $imageTmp['0'] ?? '',
                    'time' => strtotime($v['create_time']),
                    'distance' => round($singleUserInfo['distance'],2),
                    'sex' => (int) $singleUserInfo['sex'],
                    'age' => $singleUserInfo['birthday'] ? Functions::birthday($singleUserInfo['birthday']) : 0,
                ];

                $tmp['distance'] = User::handleDistance($levelInfo,$singleUserInfo,$tmp['distance']);


//                if($levelInfo['show_nearby'] == Status::COMMON_RADIO_NO ){
//                    $tmp['distance'] = ">100KM";
//                } else {
////                    $tmp['distance'] = $tmp['distance'] ? $tmp['distance'].'KM' : '未知';
//                    $tmp['distance'] = $tmp['distance'].'KM';
//                }

                $result[] = $tmp;

            }

            # 设为已读
            static::updateData(['is_read' => Status::COMMON_RADIO_YES],['id' => ArrayHelper::getColumn($list,'id')]);

            // 未读数量
            (new FriendApply())->notReadApplyNum($user['id']);
            $data['data'] = $result;
            return Functions::formatRestAPI(0, '', $data);
        }catch(Exception $e){
            return Functions::formatRestAPI(1,$e->getMessage());
        }
    }

}
